package org.epidroid.epidroid.androsoul.engine.conversation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;

/*
 * Contains the list of opened conversations
 * TODO: sort the items on update
 */
public class OpenedConversations {

	List<Conversation> _list = null;

	public List<Conversation> getList() {
		return _list;
	}

	public OpenedConversations() {
		_list = new ArrayList<Conversation>();
	}

	private Conversation getConv(NetsoulContact c) {
		synchronized (_list) {
			for (Iterator<Conversation> it = _list.iterator(); it.hasNext();) {
				Conversation item = (Conversation) it.next();
				if (item.getContact() == c) {
					return item;
				}
			}
			return null;
		}
	}

	public void contactMessage(NetsoulContact c) {
		Conversation conv = getConv(c);
		if (conv == null)
			conv = openConversation(c);
		else
			incConversationNbMsg(c);
		conv.incNbUnread();
	}

	private void openConversation(Conversation c) {
		synchronized (_list) {
			_list.add(0, c);
		}
	}

	public Conversation openConversation(NetsoulContact c) {
		Conversation conv = getConv(c);
		if (conv != null)
			return conv;
		conv = c.getConversation();
		openConversation(conv);
		return conv;
	}

	private void incConversationNbMsg(NetsoulContact c) {
		synchronized (_list) {
			for (Iterator<Conversation> it = _list.iterator(); it.hasNext();) {
				Conversation item = (Conversation) it.next();
				if (item.getMessages() == c) {
					item.incNbUnread();
					it.remove();
					_list.add(0, item);
					return;
				}
			}
		}
	}

	public void closeConversation(NetsoulContact c) {
		synchronized (_list) {
			for (Iterator<Conversation> it = _list.iterator(); it.hasNext();) {
				Conversation item = (Conversation) it.next();
				if (item.getContact() == c) {
					it.remove();
					return;
				}
			}
		}
	}

	/*
	 * Return the conversation following
	 */
	public Conversation getNext(Conversation c) {
		int index = _list.lastIndexOf(c);
		if (index == -1)
			return null;

		if (index == _list.size() - 1)
			return _list.get(0);

		return _list.get(index + 1);
	}

	/*
	 * Return the conversation preceeding
	 */
	public Conversation getPrev(Conversation c) {
		int index = _list.lastIndexOf(c);
		if (index == -1)
			return null;

		if (index == 0)
			return _list.get(_list.size() - 1);

		return _list.get(index - 1);
	}

	public void clear() {
		_list.clear();
	}

}
